﻿using MediatR;
using S.Produce.Domains;
using S.Produce.Infrastructure;
using S.Produce.Read.Api.Application.Commands.HistoryCommands;

namespace S.Produce.Read.Api.Application.CommandHandlers.HistoryCommandHandlers
{
    /// <summary>
    /// 根据耳号获取种母历史记录信息
    /// </summary>
    public class HistoryEarselCommandHandler : IRequestHandler<HistoryEarselCommand, History>
    {
        private readonly IRepository<History> _repository;

        /// <summary>
        /// 构造方式注入
        /// </summary>
        /// <param name="repository"></param>
        public HistoryEarselCommandHandler(IRepository<History> repository)
        {
            _repository = repository;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception
        public async Task<History> Handle(HistoryEarselCommand request, CancellationToken cancellationToken)
        {
            var list = await _repository.SelAllAsync(x => x.Earbugles.Equals(request.EarNumber));
            var maxDate = list.Where(x => !x.IsDel && !x.IsEnd).Select(x => new
            {
                date = x.BreedingDate,
            }).Max(a => a.date);
            var res = list.Where(x => x.BreedingDate == maxDate).FirstOrDefault();
            if (res != null)
            {
                return res;
            }
            return new History() { AtPresentParity = list.Count() };
        }
    }
}
